package com.dm.webCrawler.framework.config.properties;

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.dm.webCrawler.common.exception.CustomException;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

@Component
@ConfigurationProperties(prefix = "lb.document-server")
public class OfficeDocumentServer {
	private String addr;

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}
	
	public String getConvertUrl() {
		return getAddr()+"/ConvertService.ashx";
	}
	/**
	 * 文件转换
	 * @param params
	 * @return 返回文件http地址
	 */
	public String executConvert(Map<String, Object> params) {
		// TODO Auto-generated method stub
		HttpResponse resp = HttpUtil.createPost(getConvertUrl()).header("Content-Type", "application/json").header("accept", "application/json").body(JSONObject.toJSONString(params)).execute();
		if(resp.getStatus()!=200) {
			throw new CustomException("文件转换失败！");
		}else {
			JSONObject repBody = JSONObject.parseObject(resp.body());
			if(repBody.containsKey("endConvert") && !repBody.getBooleanValue("endConvert")) {
				try {
					Thread.currentThread().sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}//等待两秒
				return executConvert(params);
			}else if(repBody.containsKey("fileUrl")){
				return repBody.getString("fileUrl");
			}else if(repBody.containsKey("error")){
				int code=repBody.getIntValue("error");
				if(code==-1) {
					throw new CustomException("文件转换未知错误！");
				}else if(code==-2) {
					throw new CustomException("文件转换超时错误！");
				}else if(code==-3) {
					throw new CustomException("文件转换错误！");
				}else if(code==-4) {
					throw new CustomException("文件转换下载要转换的文档文件时出错！");
				}else if(code==-5) {
					throw new CustomException("文件转换密码错误！");
				}else if(code==-6) {
					throw new CustomException("文件转换访问转换结果数据库时出错！");
				}else if(code==-7) {
					throw new CustomException("文件转换参数错误！");
				}else if(code==-8) {
					throw new CustomException("文件转换令牌无效！");
				}
			}
			throw new CustomException("文件转换未知异常！:"+repBody.toJSONString());
		}
	}
	
}
